package com.xd.clap.utils;

import com.alibaba.fastjson.JSON;
import com.xd.clap.entity.request.CodeParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Component
public class CodeUtils {

    @Autowired
    private RedisUtil redisUtil;

    private static CodeUtils codeUtils;

    // 初始化
    @PostConstruct
    public void init() {
        codeUtils = this;
        codeUtils.redisUtil = this.redisUtil;
    }

    public static String getCode(String phone) {
        String host = "https://api.028lk.com";
        String path = "/Sms/Api/Send";
        String method = "POST";
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json; charset=UTF-8");

        Long time = System.currentTimeMillis();
        // 随机生成6位验证码
        String num = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        System.out.println(num);

        // 设置验证码内容
        String content = "您的验证码为："+num+"，有效期为90秒,请妥善保管。";

        // 构造CodeParam对象
        CodeParam codeParam = new CodeParam();
        codeParam.setSecretName("JXSK00025087");
        codeParam.setSecretKey("6YEdfwjcj59MBi9A");
        codeParam.setTimeStamp(time);
        codeParam.setMobile(phone);
        codeParam.setContent(content);
        codeParam.setTemplateId("");
        codeParam.setExtCode("");
        codeParam.setSignName("");
        codeParam.setTiming("");
        codeParam.setCustomId("");

        String requestJson = JSON.toJSONString(codeParam);

        try {
            // 发送POST请求
            HttpUtils.doPost(host, path, method, headers, null, requestJson);
            return num;
        } catch (Exception e) {
            log.error("---------------发送验证码错误------------------");
            e.printStackTrace();
            return "发送验证码错误";
        }
    }
}

